package com.liming.purchaseschema.core.biz;

import com.liming.core.util.config.CouchdbConfig;
import com.liming.purchaseschema.api.biz.IPurchaseSchemaService;
import com.liming.purchaseschema.core.model.SchemaDefine;
import org.lightcouch.CouchDbClient;
import org.lightcouch.Document;
import org.lightcouch.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类描述：
 * @创建人：wangkr
 * @创建时间：2014-04-14 下午2:59
 * @修改人：
 * @修改时间：
 * @修改备注：
 */

public class PurchaseSchemaServiceImpl implements IPurchaseSchemaService {
    private static CouchDbClient dbClient;

    public void init() {
        CouchdbConfig.getCouchdbConfig().setDbName("dsa_purchaseschema");
        dbClient = new CouchDbClient(
                CouchdbConfig.getCouchdbConfig().getDbName(),
                true,
                "http",
                CouchdbConfig.getCouchdbConfig().getHost(),
                CouchdbConfig.getCouchdbConfig().getPort(),
                CouchdbConfig.getCouchdbConfig().getUsername(),
                CouchdbConfig.getCouchdbConfig().getPassword());
    }

    @Override
    public List findPurchaseSchema() {
        List<SchemaDefine> list = dbClient.view("find/findPurchaseSchema").includeDocs(true).query(SchemaDefine.class);

        return list;
    }

    @Override
    public List findPurchaseSchemaByParent(Object object) {
        SchemaDefine schemaDefine = (SchemaDefine) object;
        List<SchemaDefine> schemaDefineList = dbClient.view("find/findPurchaseSchemaByParentList").key(schemaDefine.getId()).includeDocs(true).query(SchemaDefine.class);
        return schemaDefineList;
    }

    @Override
    public SchemaDefine addSchemaDefine(Object message) {
        Response response = dbClient.save(message);
        SchemaDefine foo = dbClient.find(SchemaDefine.class, response.getId());
        return foo;
    }

    @Override
    public SchemaDefine updateSchemaDefine(Object message) {
        Response response = dbClient.update(message);
        SchemaDefine foo = dbClient.find(SchemaDefine.class, response.getId());
        return foo;
    }

    @Override
    public void deleteSchemaDefine(Object message) {

        if (null != message) {
            SchemaDefine foo = (SchemaDefine) message;
            List<SchemaDefine> schemaDefineList = findPurchaseSchemaByParent(foo);
            dbClient.remove(foo);
            if (null != schemaDefineList && schemaDefineList.size() > 0) {
                for (SchemaDefine schemaDefine : schemaDefineList) {
                    deleteSchemaDefine(schemaDefine);
                }
            }
        }
    }

    @Override
    public void putSchemaDefine(Object message) {
        if (null != ((SchemaDefine) message).getRevision()) {
            updateSchemaDefine(message);
        } else {
            addSchemaDefine(message);
        }
    }

    @Override
    public void destroy() {
        dbClient.shutdown();
    }
}


